package tool.soft

import java.io.File
import akka.stream.Materializer
import akka.stream.scaladsl.Sink
import akka.util.ByteString
import dao._
import implicits.Implicits._
import models.Tables
import models.Tables._
import org.joda.time.DateTime
import play.api.data.FormBinding
import play.api.libs.ws.WSClient
import play.api.mvc.{AnyContent, Request}
import play.twirl.api.Html
import shared.Pojo._
import shared.VarTool
import tool.Pojo._
import tool.plot.AllPlot._
import tool.plot._
import tool.soft.AllSoft.SoftBT
import tool._
import utils.Utils

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
import scala.concurrent.duration._
import scala.language.postfixOps
import play.api.i18n.Messages
import upickle.default._

/** Created by yz on 15/9/2020
  */
object EnrichSoft extends EnrichSoftT with SoftBT {

  override def getFileInfos(workspaceDir: File, index: Int)(implicit
      matrixFileDataDao: MatrixFileDataDao,
      messages: Messages
  ): List[FileInfoData] = {
    List(
      FileInfoData("MSEA_Result.csv", messages("mSEAResult")),
      FileInfoData("Enrichment_Barplot.pdf", messages("enrichmentBarplot")),
      FileInfoData("Network.pdf", messages("network")),
      FileInfoData("MSEA_Network.json", messages("mSEANetwork"))
    )
  }

  override def produceConfigFile(workspaceDir: File, index: Int)(implicit
      request: Request[AnyContent],
      formBinding: FormBinding
  ) = {
    Utils.t2ConfigFile(data, Tool.getCalculateConfigJsonFile(workspaceDir))
    plot.EnrichBar.initConfigFile(workspaceDir, "")
    plot.EnrichNetwork.initConfigFile(workspaceDir, "")
    Utils.t2ConfigFile(workspaceDir, data)
  }

  override def getResultHtml(missionId: Int)(implicit request: Request[AnyContent], messages: Messages): Html = {
    views.html.user.mission.enrichResult(missionId)
  }

  def getArg(implicit request: Request[AnyContent], messages: Messages, formBinding: FormBinding): ujson.Value = {
    val basicJson = ujson.Obj(
      "metabolite set library" ->
        VarTool.libTypeMap(data.libType)
    )
    basicJson
  }

  override def produceInput(workspaceDir: File, resultDir: File)(implicit dao: MyDao): Unit = {
    super.produceInput(workspaceDir, resultDir)
    val rawDataFile = new File(workspaceDir, "AllMet_Raw.txt")
    Tool.produceKeggInfoFile(rawDataFile, workspaceDir)
  }

  override def getCommandData(workspaceDir: File, resultDir: File, index: Int): List[CommandData] = {
    val solutionFile = new File(Tool.dataDir, "color_solution/color_solution_1.txt")
    val command =
      s"""
         |${Tool.rScript} ${new File(Tool.rPath, "anno.R").unixPath}
         |${"Rscript".condaPath()} ${new File(
          Tool.rPath,
          "enrich_id_mapping.R"
        ).unixPath} --d ${Tool.databaseDir.unixPath}
         |${"Rscript".condaPath()} ${new File(
          Tool.rPath,
          "enrich_analysis.R"
        ).unixPath} --d ${Tool.databaseDir.unixPath}
           """.stripMargin
    val plotCommands = List(
      plot.EnrichBar.getCommand(workspaceDir, ""),
      plot.EnrichNetwork.getCommand(workspaceDir, "")
    )
    List(CommandData(workspaceDir, List(command) ::: plotCommands))
  }

  override def getHtml(missionName: String, missionId: Option[Int])(implicit
      request: Request[AnyContent],
      messages: Messages
  ): Html = {
    views.html.user.soft.enrich(missionName, missionId)
  }

  override def getMission(implicit
      request: Request[AnyContent],
      matrixFileDataDao: MatrixFileDataDao,
      messages: Messages,
      formBinding: FormBinding
  ): Tables.MissionRow = {
    val input = List(data.file)
    val hasLibInputs = input
    val argJson = getArg
    MissionRow(
      id = 0,
      missionName = s"${data.missionName}",
      kind = nameStr,
      userId = userId,
      startTime = new DateTime(),
      state = "preparing",
      arg = argJson,
      input = hasLibInputs
    )
  }

  override def produceInputFile(
      workspaceDir: File
  )(implicit request: Request[AnyContent], dao: MyDao, formBinding: FormBinding): Any = {
    val rawDataFile = new File(workspaceDir, "AllMet_Raw.txt")
    Tool.produceRawMetaboliteFile(userId, data.file, rawDataFile)
  }

  override def data(implicit request: Request[AnyContent], formBinding: FormBinding) = {
    FormTool.enrichForm.bindFromRequest().get
  }

}
